package com.song.web;

import com.song.bean.Role;
import com.song.bean.Users;
import com.song.service.impl.RoleServiceImpl;
import com.song.service.impl.UsersServiceImpl;
import com.song.util.PageUtils;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = "/power/user/usermanager")
public class UserServlet extends HttpServlet {
    private UsersServiceImpl usersService = new UsersServiceImpl();
    private RoleServiceImpl roleService = new RoleServiceImpl();

    /**
     * 根据method的值，判断下一步操作
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    @Override
    protected void service(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String method = req.getParameter("method");
        if ("select".equals(method)) {
            select(req, resp);
        } else if ("insert".equals(method)) {
            insert(req, resp);
        } else if ("update".equals(method)) {
            update(req, resp);
        } else if ("findById".equals(method)) {
            findById(req, resp);
        } else if ("delete".equals(method)) {
            delete(req, resp);
        }
        if ("user_select_role".equals(method)) {
            user_select_role(req, resp);
        }
    }

    /**
     * 删除用户
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void delete(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取用户ID
        String userid = req.getParameter("userid");
        //调用service
        int id = (userid == null || userid.length() == 0) ? 0 : Integer.parseInt(userid);
        Boolean aBoolean = usersService.deleteUser(id);
        if (aBoolean) {
            resp.getWriter().println("<script>alert('删除成功');location.href='/power/user/usermanager?method=select'</script>");
        } else {
            resp.getWriter().println("<script>alert('删除失败');location.href='/power/user/usermanager?method=select'</script>");
        }

    }

    /**
     * 通过用户ID找到用户信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void findById(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //从前端获取用户ID
        String userid = req.getParameter("userid");
        //调用service
        int id = (userid == null || userid.length() == 0) ? 0 : Integer.parseInt(userid);
        Users user = usersService.findById(id);
        System.out.println();
        List<Role> roles = roleService.getRoles();
        if (user != null) {
            req.setAttribute("roles", roles);
            req.setAttribute("user", user);
            req.getRequestDispatcher("edit.jsp").forward(req, resp);
        } else {
            resp.getWriter().println("<script>alert('该用户不存在');location.href='/power/user/usermanager?method=select'</script>");

        }


    }


    /**
     * 修改用户信息
     *
     * @param req
     * @param resp
     * @throws ServletException
     * @throws IOException
     */
    private void update(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端新增用户数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String realname = req.getParameter("realname");
        String sex = req.getParameter("sex");
        String roleid = req.getParameter("roleid");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String cardid = req.getParameter("cardid");
        String introduction = req.getParameter("introduction");
        String userid = req.getParameter("userid");
        //将数据分装到一个user对象中
        Users user = new Users();
        user.setLoginName(username);
        user.setPassword(password);
        user.setRealname(realname);
        user.setSex((sex == null || sex.length() == 0) ? 1 : Integer.parseInt(sex));
        user.setRoleId((roleid == null || roleid.length() == 0) ? 1: Integer.parseInt(roleid));
        user.setEmail(email);
        user.setPhone(phone);
        user.setAddress(address);
        user.setCardid(cardid);
        user.setIntroduction(introduction);
        user.setUserid(Integer.parseInt(userid));
        Boolean aBoolean = usersService.updateUser(user);
        if (aBoolean) {

            resp.getWriter().println("<script>alert('修改成功');location.href='/power/user/usermanager?method=select'</script>");
        } else {
            resp.getWriter().println("<script>alert('修改失败');location.href='/power/user/usermanager?method=findById&userid=" + userid + "'</script>");
        }
    }

    /**
     * 新增用户
     *
     * @param req
     * @param resp
     */
    private void insert(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取前端新增用户数据
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        String realname = req.getParameter("realname");
        String sex = req.getParameter("sex");
        String roleid = req.getParameter("roleid");
        String email = req.getParameter("email");
        String phone = req.getParameter("phone");
        String address = req.getParameter("address");
        String cardid = req.getParameter("cardid");
        String introduction = req.getParameter("introduction");
        //将数据分装到一个user对象中
        Users user = new Users();
        user.setLoginName(username);
        user.setPassword(password);
        user.setRealname(realname);
        user.setSex((sex == null || sex.length() == 0) ? 1 : Integer.parseInt(sex));
        user.setRoleId((roleid == null || roleid.length() == 0) ? 1 : Integer.parseInt(roleid));
        user.setEmail(email);
        user.setPhone(phone);
        user.setAddress(address);
        user.setCardid(cardid);
        user.setIntroduction(introduction);
        //调用service
        Boolean aBoolean = usersService.insertUser(user);
        if (aBoolean) {
            resp.getWriter().println("<script>alert('添加成功');location.href='/power/user/usermanager?method=select'</script>");
        } else {
            resp.getWriter().println("<script>alert('添加失败');location.href='/power/user/rolemanager?method=user_select_role'</script>");
        }
    }

    /**
     * 查询用户信息
     *
     * @param req  请求
     * @param resp 响应
     * @throws ServletException
     * @throws IOException
     */
    public void select(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取页面数据(分页查询数据)
        String index = req.getParameter("index");
        int pageIndex = (index == null || index.length() == 0) ? 1 : Integer.parseInt(index);
        System.out.println(pageIndex);
        //调用分页工具pageUtils，调用service层
        PageUtils utils = new PageUtils();
        System.out.println("---------");
        List<Users> usersList = usersService.getUser(pageIndex, utils.getPagesize());
        System.out.println(usersList.size() + "=======");
        //总信息数
        Integer totalUser = usersService.getTotalUser();
        System.out.println(totalUser);
        if (usersList != null && usersList.size() > 0) {
            //request中储存usersList
            req.setAttribute("list", usersList);
            //request存当前页码index，总信息数，总页码
            utils.setTotal(totalUser);
            utils.setIndex(pageIndex);
            req.setAttribute("page", utils);
            req.getRequestDispatcher("list.jsp").forward(req, resp);
        } else {
            resp.getWriter().println("<script>alert('没有信息');location.href='/power/user/list.jsp'</script>");
        }


    }

    /**
     * 用户页面角色的查询，查询共有几种角色供用户选择
     *
     * @param req  请求
     * @param resp 响应
     * @throws ServletException
     * @throws IOException
     */
    public void user_select_role(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //获取请求数据
        //调用service
        List<Role> roleList = roleService.getRoles();
        //roleList不为空，存值跳转
        if (roleList != null && roleList.size() != 0) {
            req.setAttribute("roles", roleList);
            req.getRequestDispatcher("add.jsp").forward(req, resp);
        }
    }

}
